﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

using EShop.Core;
using EShop.Core.Caching;
using EShop.Core.Data;
using EShop.Core.Events;
using EShop.Core.Model.Account;
using EShop.SMS;

namespace EShop.Services.Account
{

    public class MemberService : IMember
    {
        #region Constants
        private const string MEMBER_BY_ID_KEY = "EShop.Member.id-{0}";
        private const string MEMBER_PATTERN_KEY = "Era.Member";
        #endregion

        #region Fields
        private readonly IRepository<Member> _memberRepository;
        private readonly IRepository<MemberInfo> _memberinfoRepository;
        private readonly IRepository<Favorite> _favoriteRepository;
        private readonly ISMSSender _smsSender;
        private readonly ICacheManager _cacheManager;
        private readonly IEventPublisher _eventPublisher;

        //private readonly IDbContext _context;
        #endregion

        #region Ctor
        public MemberService(IRepository<Member> memberRepository,IRepository<MemberInfo> memberinfoRepository,IRepository<Favorite> favoriteRepository, ICacheManager cacheManager, IEventPublisher eventPublisher,ISMSSender smsSender)
        {
            _memberRepository = memberRepository;
            _memberinfoRepository = memberinfoRepository;
            _favoriteRepository = favoriteRepository;
            _cacheManager = cacheManager;
            _eventPublisher = eventPublisher;
            _smsSender = smsSender;
        }
        #endregion

        #region Methods
        /// <summary>
        /// 创建一个用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns>1,创建成功，-2，用户名为空，-3，用户密码为空，-4，用户已经存在</returns>
        public int CreateMeber(Member model)
        {
            if (model == null) throw new ExtException("NUll Member Model");
            if (string.IsNullOrEmpty(model.UserName)) return -2;
            if (string.IsNullOrEmpty(model.UserPwd)) return -3;
            model.UserState = 0;
            int member = _memberRepository.Table.Where(c => c.UserName.ToLower() == model.UserName.ToLower()).Count();
            if (member > 0) return -4;
            int rs = _memberRepository.Insert(model);
            if (rs > 0)
            {
                rs = 1;
                //event notification
                _eventPublisher.EntityInserted(model);

            }
            return rs;
        }
        /// <summary>
        /// 修改一个用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateMember(Member model)
        {
            if (model == null) throw new ExtException("NUll Member Model");

            int rs = _memberRepository.Update(model);
            if (rs > 0)
            {
                //event notification
                _eventPublisher.EntityUpdated(model);

            }
            return rs > 0 ? true : false;
        }
        /// <summary>
        /// 删除一个用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DelMember(string id)
        {
            var model = _memberRepository.GetById(id);
            if (model == null)
                throw new ArgumentNullException("NUll Brand Model");
            //标记为删除的用户
            model.UserState = -1;
            int r = _memberRepository.Update(model);

            if (r > 0)
            {
                //cache
                _cacheManager.Remove(string.Format(MEMBER_BY_ID_KEY,model.Id));

                //event notification
                _eventPublisher.EntityDeleted(model);
            }
            return r > 0 ? true : false;

        }

        /// <summary>
        /// 用户登陆验证
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool CheckUser(string username,string userpwd)
        {
            var query = _memberRepository.Table;
            query = query.Where(c => c.UserPwd.ToLower() == username && c.UserPwd == userpwd && c.UserState == 1);
            if (query.Count() > 0) return true;

            return false;
            
        }

        /// <summary>
        /// 验证电子邮件是否已经存在
        /// </summary>
        /// <param name="useremail"></param>
        /// <param name="checktype">1,检查用户名，2检查邮箱，3。邮箱和用户名</param>
        /// <returns></returns>
        public bool CheckUserEmail(string userORemail,int checktype=1)
        {
            bool r = false;
            userORemail=userORemail.Trim().ToLower();
            var query = _memberRepository.Table;
            if (checktype == 1) query = query.Where(c => c.UserName.ToLower() == userORemail);
            if (checktype == 2) query = query.Where(c => c.Email.ToLower() == userORemail);
            if (checktype == 3) query = query.Where(c => c.Email.ToLower() == userORemail.ToLower() || c.UserName.ToLower() == userORemail);
            if(query.Count()>0 &&(checktype==1||checktype==2||checktype==3)) r=true;
            return r;

            
        }

        /// <summary>
        /// 通过用户名取得用户id
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public int GetUserIdByName(string username)
        {
            username=username.ToLower().Trim();
            var query = _memberRepository.Table.Where(c => c.UserName.ToLower() == username).FirstOrDefault();
            if (query != null) return query.Id;
            return 0;
        }
        /// <summary>
        /// 修改密码提示问题
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool ChangePwdAnswer(string username,string olduserpwdq,string olduserpwda,string newuserpwdq,string newuserpwda)
        {
            var model = _memberRepository.Table.Where(c => c.UserName == username.Trim().ToLower()).FirstOrDefault();
            bool ret = false;
            if (model != null)
            {
                if (model.UserPwdQuestion == olduserpwdq && model.UserPwdAnswer == olduserpwda)
                {
                    model.UserPwdQuestion = newuserpwdq;
                    model.UserPwdAnswer = newuserpwda;
                    int rs = _memberRepository.Update(model);
                    if (rs > 0)
                    {
                        _eventPublisher.EntityUpdated(model);
                        ret = true;
                    }
                }
            }
            return ret;
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool ChangePwd(string username, string oldpwd,string newpwd)
        {
            username = username.Trim().ToLower();
            oldpwd = oldpwd.Trim();
            bool ret = false;
            var model = _memberRepository.Table.Where(c=>c.UserName==username&&c.UserPwd==oldpwd).FirstOrDefault();
            if (model != null)
            {
                model.UserPwd = newpwd;
               int rs=  _memberRepository.Update(model);
               if (rs > 0)
               {
                   _eventPublisher.EntityUpdated(model);
                   ret = true;
               }
            }
            return ret;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="showHidden"></param>
        /// <returns></returns>
        public IList<Member> GetAllMember(bool showHidden = false)
        {
            var query = _memberRepository.Table;
            if (!showHidden)
                query = query.Where(c => c.UserState==1);

            query = query.OrderBy(c => c.Id);
            var sortedMember = query.ToList();

            //sort categories

            return sortedMember;
        }

        /// <summary>
        /// 获取所有用户信息分页
        /// </summary>
        /// <param name="start"></param>
        /// <param name="limit"></param>
        /// <param name="fiter"></param>
        /// <returns></returns>
        public IPagedList<Member> GetAllMember(int pageIndex, int pageSize, bool showHidden = false)
        {

            var Brand = GetAllMember(showHidden);
            //filter
            return new PagedList<Member>(Brand, pageIndex, pageSize);
        }
        /// <summary>
        /// 获取一条用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Member GetMemberInfoByid(int Id)
        {
            var member = _memberRepository.GetById(Id);
            member.memberinfo = _memberinfoRepository.Table.Where(c => c.UserId == Id).FirstOrDefault();
            return member;
        }


        /// <summary>
        /// 取得短信密码
        /// </summary>
        /// <param name="smspass"></param>
        /// <param name="sitepass"></param>
        /// <param name="?"></param>
        public void GetSmsPassInfo(ref string smspass, ref string sitepass, ref string smsRpass)
        {
            
            //DataTable dt = new DataTable();
            //DataTable dt1 = new DataTable();
            //string str_sql = "select * from  [tb_mc_sms] '";
            //string str_sql1 = "select * from [tb_mc_config] where id=5,or id=16 order by id desc";
            //Library.SqlProvider.OleDb db = new Library.SqlProvider.OleDb();

            //try
            //{
            //    dt = db.ExecuteDataset(COMM.PucConfig.ConnectionStringA, CommandType.Text, str_sql).Tables[0];
            //    dt1 = db.ExecuteDataset(COMM.PucConfig.ConnectionStringA, CommandType.Text, str_sql1).Tables[0];
            //}
            //catch (Exception ex) { }
            //smsRpass = dt.Rows[0]["smspass"].ToString();
            //smspass = dt1.Rows[0]["value"].ToString();
            //sitepass = dt1.Rows[1]["value"].ToString();

        }
        /// <summary>
        /// 设置短信一次性密码
        /// </summary>
        /// <param name="smsRpass"></param>
        /// <returns></returns>
        public bool SetSmsPass(string smsRpass)
        {

            bool ret = false;
            //string str_sql = "update  [tb_mc_sms] set smspass='" + smsRpass + "'";
            //Library.SqlProvider.OleDb db = new Library.SqlProvider.OleDb();
            //DataTable dt = new DataTable();
            //try
            //{
            //    dt = db.ExecuteDataset(COMM.PucConfig.ConnectionStringA, CommandType.Text, str_sql).Tables[0];
            //}
            //catch (Exception ex) { }

            return ret;
        }
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="MobileNo"></param>
        /// <param name="Smscontent"></param>
        /// <param name="Rcontent"></param>
        public void SendMsg(string smspass, string smsrpass, string sitepass, string MobileNo, string Smscontent, ref string Rcontent)
        {
            //string url = "http://www.mcvrlab.com/content/webservices/sms.ashx?no=" + MobileNo + "&x_passo=" + smsrpass + "&x_pass=" + sitepass + "&x_content=" + Smscontent + "&x_sitepass" + sitepass;
            //MSXML2.XMLHTTP xre = new XMLHTTP();
            //xre.open("GET", url, false, null, null);
            //xre.send("");
            //Rcontent = xre.responseText.ToString();
        }
        /// <summary>
        /// 取得收藏夹
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public IList<Favorite> GetFav(int userid,int pageIndex, int pageSize)
        {
            var query = _favoriteRepository.Table.Where(c => c.UserId == userid);
            return new PagedList<Favorite>(query, pageIndex, pageSize);
        }
        /// <summary>
        /// 设置收藏夹
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="fav"></param>
        /// <returns></returns>
        public bool SetFav(int userid, int fav)
        {
            bool ret = false;

            var query = _favoriteRepository.Table.Where(c => c.UserId == userid && c.ProductId == fav).FirstOrDefault();
            //如果没有搜藏过改产品
            if (query == null)
            {
                Favorite p = new Favorite();
                p.UserId =userid;
                p.ProductId = fav;
                if (_favoriteRepository.Insert(p) > 0)
                {
                    ret = true;
                    _eventPublisher.EntityInserted(p);
                }
            }
            return ret;
        }
        #endregion
    }
}
